package com.xueliman.iov.auth_server_feign_common.advice;

import com.alibaba.fastjson.JSONObject;
import com.xueliman.iov.cloud.framework.web.exception.ApiException;
import com.xueliman.iov.cloud.framework.web.vo.SingleResultBundle;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.IOException;

/**
 * @author zxg
 * 复写原有默认feign异常解析类
 */
@Slf4j
public class OpenFeignErrorDecoder implements ErrorDecoder {
    /**
     * Feign异常解析
     * @param methodKey 方法名
     * @param response 响应体
     */
    @Override
    public Exception decode(String methodKey, Response response) {
        log.error("feign client error,response is {}:",response);
        try {
            //获取数据
            String errorContent = IOUtils.toString(response.body().asInputStream());

            SingleResultBundle<?> resultData = JSONObject.parseObject(errorContent,SingleResultBundle.class);
            if(!resultData.isSuccess()){
                log.error("熔断/限流 ---------- 接口地址：" + response.request().url() + ", 存在错误：" + resultData.getMessage());
                throw new ApiException(resultData.getMessage());
//                return new ApiException(resultData.getMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new ApiException("Feign client 调用异常");
    }
}
